package com.diors.commons.network;

import java.nio.ByteOrder;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;

import com.diors.commons.log.DiorsLogger;

/**
 * 连接工厂
 * @author	darren.ouyang
 * @data	2013-9-10
 */
public abstract class DiorsConnFactory
{

	static final DiorsLogger log = DiorsLogger.getLogger(DiorsConnFactory.class);
	
	/**
	 * 创建一个新的连接
	 * @param ctx			netty连接上下文对象
	 * @param dispatcher	调度器
	 * @return
	 * @create	2013-9-10	darren.ouyang
	 */
	public DiorsConnection createConnection (ChannelHandlerContext ctx, Dispatcher dispatcher)
	{
		DiorsConnection conn = createConnection();
		
		conn.channel = ctx;
		conn.dispatcher = dispatcher;
		/*动态长度的，因netty写入消息执行可能在执行包队列的线程中，可能会不用这个缓冲流，所以这里暂时初始化长度比较小*/
		conn.writeBuffer = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 256);
		/*定死长度，初始化设置5K*/
		conn.readBuffer = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, 5 * 1024);
		
		conn.ip = ctx.getChannel().getRemoteAddress().toString();
		
		if (!ctx.getChannel().isOpen())
		{
			log.error("连接尚未打开!");
			return null;
		}
		
		afterCreateConn(conn);
		return conn;
	}
	
	protected abstract DiorsConnection createConnection ();
	
	/**
	 * 默认的创建连接之后处理方法
	 * @create	2013-9-10	darren.ouyang
	 */
	protected void afterCreateConn (DiorsConnection conn){}
}
